package com.example.a22310.myapplication.ViewModel.Club;

import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import com.example.a22310.myapplication.Beans.user;
import com.example.a22310.myapplication.Listener.ClubListener;
import com.example.a22310.myapplication.Model.ClubModel;
import com.example.a22310.myapplication.databinding.ActivityVideoDetailBinding;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

public class VideoDetailViewModel implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
        SeekBar.OnSeekBarChangeListener,ClubListener<user> {
    private ActivityVideoDetailBinding binding;
    private AppCompatActivity activity;
    private MediaPlayer mediaPlayer;//多媒体播放器

    private SurfaceHolder holder;//****************SurfaceHolder接口为一个显示界面内容的容器

    private static int savedPosition;//===============记录当前播放文件播放的进度
    private static String savedFilepath;//===============记录当前播放文件的位置
    private Timer timer;//===============定义一个计时器，每隔100ms更新一次进度条
    private TimerTask task;//===============计时器所执行的任务


    private  String filepath;

    private boolean screenFlag = false;

    private boolean attentionFlag = false;

    private int userid,videoid,clubid;

    public static boolean SENDSIGN = false;


    public VideoDetailViewModel(AppCompatActivity activity, ActivityVideoDetailBinding binding,String filepath,
                                int userid,int videoid,int clubid){
        this.activity = activity;
        this.binding = binding;
        this.filepath = filepath;
        this.userid = userid;
        this.videoid = videoid;
        this.clubid = clubid;
        initialize();
        binding.setDetail(this);
    }

    public void initialize(){
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnErrorListener(this);
        holder = binding.fullscreenContent.getHolder();//****************得到显示界面内容的容器
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //设置surfaceView自己不管理缓存区。虽然提示过时，但最好还是设置下
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {//holder被销毁时回调。最小化时都会回调
                if (mediaPlayer != null) {
                    Log.i("bqt", "销毁了--surfaceDestroyed" + "--" + mediaPlayer.getCurrentPosition());
                    savedPosition = mediaPlayer.getCurrentPosition();//当前播放位置
                    mediaPlayer.stop();
                    timer.cancel();
                    task.cancel();
                    timer = null;
                    task = null;
                }
            }
            @Override
            public void surfaceCreated(SurfaceHolder holder) {//holder被创建时回调
                Log.i("bqt", "创建了--" + savedPosition + "--" + savedFilepath);
                if (savedPosition > 0) {//如果记录的数据有播放进度。
                    try {
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(savedFilepath);
                        mediaPlayer.setDisplay(holder);
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //holder宽高发生变化（横竖屏切换）时回调
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            }
        });

        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        String hms = formatter.format(mediaPlayer.getDuration()/16/3600);
        binding.endTime.setText(hms);   //设置时间
    }


    public void back(View view ){//返回
        activity.onBackPressed();
    }

    public void playvideo(View view ){    //播放视频
        playfilm();
        binding.playVideo.setVisibility(View.GONE);
        binding.cover.setVisibility(View.GONE);
    }

    public void attention(View view ){    //收藏
        if (attentionFlag==false){
            binding.attention.setImageResource(R.drawable.ic_my_attention_red);
        }else {
            binding.attention.setImageResource(R.drawable.user_attention);
        }
    }

    public void play(View view ){    //继续和暂停
        pause();
        binding.playVideo.setVisibility(View.VISIBLE);
    }

    public void send(View view ){    //发评论
        String content = binding.editText.getText().toString();
        ClubModel clubModel = new ClubModel();
        clubModel.addVideoComment(userid,videoid,clubid,content,VideoDetailViewModel.this);
    }


    public void fill_screen(View view ){//  display("全屏播放");
        if (screenFlag == false){
            if(activity.getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                binding.layoutHide.setVisibility(View.GONE);
            }
            screenFlag = true;
        }else{
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            binding.layoutHide.setVisibility(View.VISIBLE);
            screenFlag = false;
        }
    }


    private void display(String string){
        Toast.makeText(activity,string,Toast.LENGTH_LONG).show();
    }

    public void playfilm() {   //播放
        if (!TextUtils.isEmpty(filepath)) {
            try {
                savedFilepath = filepath;
                mediaPlayer.setDataSource(filepath);
                mediaPlayer.setDisplay(holder);
                mediaPlayer.prepareAsync();//异步准备
                binding.play.setEnabled(false);
                display("准备中，可能需要点时间……");
            } catch (Exception e) {
                e.printStackTrace();
                display("播放失败，请检查是否有网络权限");
            }
        } else {
            display("路径不能为空");
        }
    }

    public void pause() {    //暂停
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                //  bt_pause.setText(STATE_CONTINUE);按钮转换
                binding.play.setImageResource(R.drawable.ic_play);
                binding.cover.setVisibility(View.GONE);
            } else {
                mediaPlayer.start();
                //  bt_pause.setText(STATE_PAUSE); 按钮转换
                binding.play.setImageResource(R.drawable.ic_pause);
                binding.cover.setVisibility(View.VISIBLE);
                return;
            }
        }
    }


    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        display("播放完毕");
        mediaPlayer.reset();
        binding.play.setEnabled(true);
        binding.playVideo.setVisibility(View.VISIBLE);
        binding.cover.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        display("报错了--" + what + "--" + extra);
        return false;
    }

    @Override
    public void onPrepared(final MediaPlayer mediaPlayer) {
        mediaPlayer.start();
        mediaPlayer.seekTo(savedPosition);//开始时是从0开始播放，恢复时是从指定位置开始播放
        binding.seekBar.setMax(mediaPlayer.getDuration());//将进度条的最大值设为文件的总时长
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                binding.seekBar.setProgress(mediaPlayer.getCurrentPosition());//将媒体播放器当前播放的位置赋值给进度条的进度
            }
        };
        timer.schedule(task, 0, 100);//0秒后执行，每隔100ms执行一次
        display("准备好了");
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.seekTo(seekBar.getProgress());//停止拖拽时进度条的进度
    }

    @Override
    public void setContentView() {

    }

    @Override
    public void initView() {

    }

    @Override
    public void initEvent() {

    }

    @Override
    public void setTitle() {

    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return false;
    }

    @Override
    public void onSuccess(user list) {
        if (list.getSuccess()==1){
            display("评论成功");
            binding.editText.setText("");
            SENDSIGN = true;
        }else{
            display("数据错误");
        }
    }

    @Override
    public void onFailure() {
        display("请确认是否联网");
    }



}
